<?php

use app\modules\Admin\models\dianpuModel;
use Illuminate\Database\Capsule\Manager as DB;

#[店铺管理]
class DianpuController extends AcommonController {

    public function init() {
        $this->model = (new dianpuModel());
        $this->table = 'dianpu';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[店铺分红设置]
    public function configAction()
    {
        if($this->isPost()){
            $postData = $this->postData;
            if(!isset($postData['dianpufenhong_self_ratio'])) {
                ret(2, '店铺分红比例出错');
            }
            if(!isset($postData['dianpufenhong_text'])) {
                ret(2, '店铺分红显示名称出错');
            }
            if(!isset($postData['dianpufenhong'])) {
                ret(2, '是否开启店铺分红出错');
            }
            if(!isset($postData['dianpufenhong_enbale_goods_id']) || !is_numeric($postData['dianpufenhong_enbale_goods_id']) || $postData['dianpufenhong_enbale_goods_id'] < 0) {
                ret(2, '店铺代理资格商品出错');
            }
            if($postData['dianpufenhong_enbale_goods_id'] > 0 && goodsModel::query()->where('id', $postData['dianpufenhong_enbale_goods_id'])->doesntExist()){
                ret(2, '店铺代理资格商品不存在');
            }
            $dianpufenhong_self_ratio = configModel::query()->where([['type', '=',19],['key','=','dianpufenhong_self_ratio']])->first();
            $dianpufenhong_text = configModel::query()->where([['type', '=',19],['key','=','dianpufenhong_text']])->first();
            $dianpufenhong = configModel::query()->where([['type', '=',19],['key','=','dianpufenhong']])->first();
            $dianpufenhong_enbale_goods_id = configModel::query()->where([['type', '=',19],['key','=','dianpufenhong_enbale_goods_id']])->first();
            try {
                DB::transaction(function () use($dianpufenhong_self_ratio, $dianpufenhong_text, $dianpufenhong, $dianpufenhong_enbale_goods_id, $postData) {
                    if($dianpufenhong){
                        $dianpufenhong->value = $postData['dianpufenhong'];
                        $dianpufenhong->updated_at = timestamp();
                        $dianpufenhong->save();
                    }else{
                        configModel::query()->insert([
                                                         'type'=>19,
                                                         'title'=>'是否开启店铺分红',
                                                         'key'=>'dianpufenhong',
                                                         'value'=>$postData['dianpufenhong'],
                                                         'tips'=>'',
                                                         'input_mode'=>'bool',
                                                         'items'=>null,
                                                         'weigh'=>299,
                                                         'created_at'=>timestamp(),
                                                         'updated_at'=>timestamp(),
                                                     ]);
                    }
                    if($dianpufenhong_text){
                        $dianpufenhong_text->value = $postData['dianpufenhong_text'];
                        $dianpufenhong_text->updated_at = timestamp();
                        $dianpufenhong_text->save();
                    }else{
                        configModel::query()->insert([
                                                         'type'=>19,
                                                         'title'=>'店铺分红显示名称',
                                                         'key'=>'dianpufenhong_text',
                                                         'value'=>$postData['dianpufenhong_text'],
                                                         'tips'=>'',
                                                         'input_mode'=>'text',
                                                         'items'=>null,
                                                         'weigh'=>298,
                                                         'created_at'=>timestamp(),
                                                         'updated_at'=>timestamp(),
                                                     ]);
                    }
                    if($dianpufenhong_self_ratio){
                        $dianpufenhong_self_ratio->value = $postData['dianpufenhong_self_ratio'];
                        $dianpufenhong_self_ratio->updated_at = timestamp();
                        $dianpufenhong_self_ratio->save();
                    }else{
                        configModel::query()->insert([
                                                         'type'=>19,
                                                         'title'=>'店铺分红自购比例',
                                                         'key'=>'dianpufenhong_self_ratio',
                                                         'value'=>$postData['dianpufenhong_self_ratio'],
                                                         'tips'=>'%',
                                                         'input_mode'=>'text',
                                                         'items'=>null,
                                                         'weigh'=>297,
                                                         'created_at'=>timestamp(),
                                                         'updated_at'=>timestamp(),
                                                     ]);
                    }
                    if($dianpufenhong_enbale_goods_id){
                        $dianpufenhong_enbale_goods_id->value = $postData['dianpufenhong_enbale_goods_id'];
                        $dianpufenhong_enbale_goods_id->updated_at = timestamp();
                        $dianpufenhong_enbale_goods_id->save();
                    }else{
                        configModel::query()->insert([
                                                         'type'=>19,
                                                         'title'=>'店铺代理资格商品',
                                                         'key'=>'dianpufenhong_enbale_goods_id',
                                                         'value'=>$postData['dianpufenhong_enbale_goods_id'],
                                                         'tips'=>'%',
                                                         'input_mode'=>'text',
                                                         'items'=>null,
                                                         'weigh'=>296,
                                                         'created_at'=>timestamp(),
                                                         'updated_at'=>timestamp(),
                                                     ]);
                    }
                });
                ret(0, '店铺分红设置成功！');
            }catch (Exception $e){
                ret(1, '店铺分红设置失败！');
            }
        }else{
            $config = [
                'dianpufenhong' => configModel::query()->where([['type', 19],['key', 'dianpufenhong']])->value('value')?:'0',
                'dianpufenhong_text' => configModel::query()->where([['type', 19],['key', 'dianpufenhong_text']])->value('value')?:'',
                'dianpufenhong_self_ratio' => configModel::query()->where([['type', 19],['key', 'dianpufenhong_self_ratio']])->value('value')?:'0.00',
                'dianpufenhong_enbale_goods_id' => configModel::query()->where([['type', 19],['key', 'dianpufenhong_enbale_goods_id']])->value('value')?:'0',
            ];
            $this->_view->assign('dataset', json_encode($config, JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/config.html');
        }
    }
    
    #[店铺列表]
    public function indexAction($returnData = FALSE)
    {
        if ($this->isPost()){
            $this->model = $this->model->with(['member']);
            $post_data = $this->postData;
            $mode = $this->get('mode', 'all');
            switch ($mode){
                case 'normal':
                    array_push($this->search,['status', '=', 1]);
                    break;
                case 'disable':
                    array_push($this->search,['status', '=', 0]);
                    break;
            }
            if(isset($post_data['dianpu_start']) && !empty($post_data['dianpu_start'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['dianpu_start']);
            }
            if(isset($post_data['dianpu_end']) && !empty($post_data['dianpu_end'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['dianpu_end']);
            }
            $keywordsTypeArray = [
                'user_id' => 'user_id',
                'user_phone' => 'user_phone',
                'apply_id' => 'apply_id'
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['member_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['apply_id']){
                    array_push($this->search, ['apply_id', '=', $post_data['keywords']]);
                }
            }
            unset($keywordsTypeArray);
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }else{
            $this->_view->assign('all_status', json_encode(['all'=>'全部', 'normal' => '正常', 'disable' => '禁用'], JSON_UNESCAPED_UNICODE));
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }
    }

    #[编辑店铺]
    public function editAction()
    {
        if(! $this->isPost()){
            $prov = DB::table('area')->where('level', 1)->get();
            $city = DB::table('area')->where('level', 2)->get();
            $area = DB::table('area')->where('level', 3)->get();
            $this->_view->assign('prov', $prov->toJson());
            $this->_view->assign('city', $city->toJson());
            $this->_view->assign('area', $area->toJson());
        }
        parent::editAction(); // TODO: Change the autogenerated stub
    }

    #[新增店铺]
    public function createAction()
    {
        if($this->isPost()){
            $postData = $this->postData;
            foreach ($postData as &$data){
                $data = trim($data);
            }
            if(empty($postData['name']) || mb_strlen($postData['name']) < 3){
                ret(2, '店铺名称 未填写或字数太少');
            }
            if(empty($postData['company_name']) || mb_strlen($postData['company_name']) < 3){
                ret(3, '企业名称 未填写或字数太少');
            }
            if(empty($postData['company_representative_name']) || mb_strlen($postData['company_name']) < 2){
                ret(4, '企业法人姓名 未填写或字数太少');
            }
            if(empty($postData['phone']) || mb_strlen($postData['phone']) < 5){
                ret(5, '联系电话 未填写或字数太少');
            }
            if(! preg_match("/^[0-9][0-9-]{5,10}[0-9]$/", $postData['phone'])){
                ret(6, '联系电话 格式错误');
            }
            if(empty($postData['area_id'])){
                ret(7, '地区 没有选择完整');
            }
            $area = areaModel::query()->where('level', 3)->where('id', $postData['area_id'])->first();
            if(!$area){
                ret(8, '县区 不存在');
            }
            $city = areaModel::query()->where('level', 2)->where('id', $postData['city_id'])->first();
            if(!$city){
                ret(9, '城市 不存在');
            }
            if($area->pid != $postData['city_id']){
                ret(10, '县区不在选择城市范围内');
            }
            $province = areaModel::query()->where('level', 1)->where('id', $postData['province_id'])->first();
            if(!$province){
                ret(11, '省份 不存在');
            }
            if($city->pid != $postData['province_id']){
                ret(12, '城市不在选择省份范围内');
            }
            $postData['province_name'] = $province->name;
            $postData['city_name'] = $city->name;
            $postData['area_name'] = $area->name;
            unset($area, $city, $province);
            if(empty($postData['address']) || mb_strlen($postData['address']) < 2){
                ret(13, '详细地址 未填写或字数太少');
            }
            if(empty($postData['member_id'])){
                ret(14, '未设置管理员');
            }
            if(memberModel::query()->where('id', $postData['member_id'])->doesntExist()){
                ret(15, '管理员不存在');
            }
            $this->cleanTableColumn($this->table, $postData);
            unset($postData['id'], $postData['deleted_at']);
            $postData['apply_id'] = 0;
            $postData['money_withdraw_freeze'] = 0.00;
            $postData['created_at'] = timestamp();
            $postData['updated_at'] = $postData['created_at'];
            try{
                DB::transaction(function () use ($postData) {
                    $this->model->insert($postData);
                });
                ret(0, '恭喜，新增店铺成功! ^_^');
            }catch (Exception $e){
                ret(1, '抱歉，新增店铺失败。');
            } finally {
                unset($postData);
            }
        }else{
            $prov = DB::table('area')->where('level', 1)->get();
            $city = DB::table('area')->where('level', 2)->get();
            $area = DB::table('area')->where('level', 3)->get();
            $this->_view->assign('prov', $prov->toJson());
            $this->_view->assign('city', $city->toJson());
            $this->_view->assign('area', $area->toJson());
            $dataset = $this->getTableColumn($this->table);
            unset($dataset['id'],$dataset['province_name']
                ,$dataset['city_name'],$dataset['area_name'],$dataset['apply_id']
                ,$dataset['money_withdraw_freeze'],$dataset['created_at'],$dataset['updated_at'],$dataset['deleted_at']);
            $this->_view->assign('dataset', json_encode($dataset));
            $this->_view->display( strtolower($this->controller) . '/create.html');
        }
    }
    #[获取可成为管理员的用户列表]
    public function getmemberlistAction()
    {
        if($this->isPost()){
            $type     = $this->get('keywordsType');
            $keywords = $this->get('keywords');
            $query = memberModel::query()->where('status', '=', 'normal')
                                         ->whereNotIn('id', dianpuModel::withTrashed()->newQuery()->pluck('member_id', 'id')->toArray())
                                         ->whereNotIn('id', \app\modules\Admin\models\dianpuapplyModel::query()->pluck('member_id', 'id')->toArray());
            if (!empty($keywords)) {
                switch ($type){
                    case 'id':
                        $query->where("id", $keywords);
                        break;
                    case 'nickname':
                        $query->where("nickname", 'like', "%{$keywords}%");
                        break;
                    case 'phone':
                        $query->where("phone", 'like', "%{$keywords}%");
                        break;
                }
            }
            $total = $query->count();
            $query = $query->select([
                                        "id",
                                        "avatar",
                                        "nickname",
                                        "phone",
                                    ]);
            $query = $query->orderByDesc('id');
            $page = $this->get('page', 1);
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $query = $query->offset($offset)->limit($limit);
            $rows = $query->get()->makeHidden(['nickname_hide'])->append('level_info');
            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->display( strtolower($this->controller) . '/getmemberlist.html');
        }
    }
    #[店铺回收站列表]
    public function recycleindexAction($returnData = FALSE)
    {
        if ($this->isPost()){
            $this->model = dianpuModel::onlyTrashed()->with(['member']);
            $mode = $this->get('mode', 'all');
            switch ($mode){
                case 'normal':
                    array_push($this->search,['status', '=', 1]);
                    break;
                case 'disable':
                    array_push($this->search,['status', '=', 0]);
                    break;
            }
            if(isset($post_data['recycleDianpu_start']) && !empty($post_data['recycleDianpu_start'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['recycleDianpu_start']);
            }
            if(isset($post_data['recycleDianpu_end']) && !empty($post_data['recycleDianpu_end'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['recycleDianpu_end']);
            }
            $keywordsTypeArray = [
                'user_id' => 'user_id',
                'user_phone' => 'user_phone',
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['member_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
            }
            unset($keywordsTypeArray);
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }else{
            $this->_view->assign('all_status', json_encode(['all'=>'全部', 'normal' => '正常', 'disable' => '禁用'], JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/recycleindex.html');
        }
    }

    #[切换店铺状态]
    public function togglestatusAction()
    {
        if ($this->isPost()){
            $id = $this->get('id', 0);
            try {
                $dianpu = $this->model->findOrFail($id);
                if($dianpu->status === 1){
                    $dianpu->status = 0;
                }else{
                    $dianpu->status = 1;
                }
                $dianpu->updated_at = timestamp();
                $dianpu->save();
                ret(0, '店铺状态切换成功');
            }catch (Exception $e){
                ret(3002, '店铺不存在');
            }

        }else{
            ret(3001, '非法提交');
        }
    }

    #[删除店铺]
    public function deleteAction()
    {
        parent::deleteAction(); // TODO: Change the autogenerated stub
    }

    #[销毁店铺]
    public function forceDeleteAction()
    {
        parent::forceDeleteAction(); // TODO: Change the autogenerated stub
    }

    #[恢复店铺]
    public function restoreAction()
    {
        parent::restoreAction(); // TODO: Change the autogenerated stub
    }
}
